package org.penguin.study.bk.base.aspect;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.penguin.study.bk.constant.CommonConstant;
import org.penguin.study.bk.dict.service.SysDictService;
import org.penguin.study.bk.base.annotation.Dict;
import org.penguin.study.bk.base.util.ConvertUtil;
import org.penguin.study.bk.base.vo.Result;
import org.penguin.study.bk.base.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

/**
 * @author chengyinghua
 */
@Aspect
@Component
@Slf4j
public class DictAspect {

    @Autowired
    private SysDictService dictService;

    @Autowired
    private ObjectMapper objectMapper;

    // 定义切点Pointcut
    @Pointcut("execution(public * org.penguin.study.bk..*.*Controller.*(..))")
    public void dictExecutionService() {
    }

    @Around("dictExecutionService()")
    public Object doAround(ProceedingJoinPoint pjp) throws Throwable {
        long time1 = System.currentTimeMillis();
        Object result = pjp.proceed();
        Signature signature = pjp.getSignature();
        if (signature.getName().contains("Page") || signature.getName().contains("Detail")) {
            parseDictText(result);
        }
        long time2 = System.currentTimeMillis();
        log.debug("获取JSON数据 耗时：" + (time2 - time1) + "ms");
        long start = System.currentTimeMillis();

        long end = System.currentTimeMillis();
        log.debug("解析注入JSON数据  耗时" + (end - start) + "ms");
        return result;
    }

    private void parseDictText(Object result) {
        if (result instanceof Result) {
            Result localResult = (Result) result;
            Object data = localResult.getResult();

            if (data instanceof IPage) {
                List<JSONObject> items = new ArrayList<>();
                for (Object record : ((IPage) data).getRecords()) {
                    JSONObject item = parseObject(record);
                    items.add(item);
                }
                localResult.setResult(items);
            } else {
                JSONObject item = parseObject(data);
                ((Result) result).setResult(item);
            }
        }
    }

    private JSONObject parseObject(Object record) {
        String json = "{}";
        try {
            //解决@JsonFormat注解解析不了的问题详见SysAnnouncement类的@JsonFormat
            json = objectMapper.writeValueAsString(record);
        } catch (JsonProcessingException e) {
            log.error("json解析失败" + e.getMessage(), e);
        }
        JSONObject item = JSONObject.parseObject(json);
        //用getAllFields替换掉getDeclaredFields：解决继承实体字段无法翻译问题------
        for (Field field : ConvertUtil.getAllFields(record)) {
            if (field.getAnnotation(Dict.class) != null) {
                String code = field.getAnnotation(Dict.class).dicCode();
                String text = field.getAnnotation(Dict.class).dicText();
                String table = field.getAnnotation(Dict.class).dictTable();
                String key = String.valueOf(item.get(field.getName()));

                //翻译字典值对应的txt
                String textValue = translateDictValue(code, text, table, key);

                log.debug(" 字典Val : " + textValue);
                log.debug(" __翻译字典字段__ " + field.getName() + CommonConstant.DICT_TEXT_SUFFIX + "： " + textValue);
                item.put(field.getName() + CommonConstant.DICT_TEXT_SUFFIX, textValue);
            }
        }
        return item;
    }

    /**
     * 翻译字典文本
     *
     * @param code
     * @param text
     * @param table
     * @param key
     * @return
     */
    private String translateDictValue(String code, String text, String table, String key) {
        if (StringUtil.isEmpty(key)) {
            return null;
        }
        StringBuilder textValue = new StringBuilder();
        String[] keys = key.split(",");
        for (String k : keys) {
            String tmpValue = null;
            log.debug(" 字典 key : " + k);
            if (k.trim().length() == 0) {
                continue; //跳过循环
            }
            if (StringUtils.hasText(table)) {
                log.debug("--DictAspect------dicTable=" + table + " ,dicText= " + text + " ,dicCode=" + code);
                tmpValue = dictService.queryTableDictTextByKey(table, text, code, k.trim());
            } else {

                tmpValue = dictService.queryDictTextByKey(code, k.trim());
            }

            if (tmpValue != null) {
                if (!"".equals(textValue.toString())) {
                    textValue.append(",");
                }
                textValue.append(tmpValue);
            }
        }
        return textValue.toString();
    }

}
